package com.googlecode.framework.web.pagination;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.UnhandledException;

public class PaginationHelper {
    
    private HttpServletRequest request;

    private HttpServletResponse response;

    public static AbstractWebPagination makeWebPagination(HttpServletRequest request, HttpServletResponse response) {
        // 生成Href
        String requestURI = request.getRequestURI();
        Href href = new DefaultHref(response.encodeURL(requestURI));
        
        // 每页记录数
        int itemsPerpage = 20;
        try {
            String strItemsPerPage = request.getParameter("");
            if (!StringUtils.isEmpty(strItemsPerPage)) {
                itemsPerpage = Integer.parseInt(strItemsPerPage);
            }
        } catch (NumberFormatException nfe) {
        }

        
        return makeWebPagination(request, 20, null);
    }
    
    public static AbstractWebPagination makeWebPagination(HttpServletRequest request, int pagesize, String excludedParams) {
        final String paginationName = request.getParameter("__paginationName");
        
        final String strPagesize = request.getParameter("");
        Href href = new DefaultHref(request.getRequestURI());
        href.setParameterMap(getParameterMap(request));
        return null;
    }
    
    public static Map getParameterMap(HttpServletRequest request) {
        Map map = new HashMap();

        // get the parameters names
        Enumeration parametersName = request.getParameterNames();
        while (parametersName.hasMoreElements()) {
            // ... get the value
            String paramName = (String) parametersName.nextElement();

            request.getParameter(paramName);
            // put key/value in the map
            String[] originalValues = (String[]) ObjectUtils.defaultIfNull(request.getParameterValues(paramName), new String[0]);
            String[] values = new String[originalValues.length];

            for (int i = 0; i < values.length; i++) {
                try {
                    values[i] = URLEncoder.encode(StringUtils.defaultString(originalValues[i]), "UTF8"); //$NON-NLS-1$
                } catch (UnsupportedEncodingException e) {
                    throw new UnhandledException(e);
                }
            }
            map.put(paramName, values);
        }

        // return the Map
        return map;
    }
}
